package com.heartech.prediciton_wx.service.message;

import com.heartech.prediciton_wx.constant.WxCode;
import com.heartech.prediciton_wx.dao.MessageDTO;
import com.heartech.prediciton_wx.constant.MessageCode;
import com.heartech.prediciton_wx.entity.qrcode.QrStrState;
import com.heartech.prediciton_wx.entity.message.BaseMessage;
import com.heartech.prediciton_wx.entity.message.TextMessage;
import com.heartech.prediciton_wx.service.qrcode.QrCodeService;
import com.heartech.prediciton_wx.service.qrcode.QrCodeStateManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
@Slf4j
public class MessageService {


    @Resource
    private QrCodeService qrCodeService;

    @Resource
    private QrCodeStateManager qrCodeStateManager;

    @Resource
    private MessageXmlService messageXmlService;

    public String processRequest(Map<String, String> paramMap) throws InstantiationException, IllegalAccessException {
        MessageDTO messageDTO = mapToDTO(paramMap);
        switch (messageDTO.getMsgType()) {
            case MessageCode.REQ_MESSAGE_TYPE_TEXT:
                log.info("这是文本消息！");
                return processTextMessage(messageDTO);
            case MessageCode.REQ_MESSAGE_TYPE_EVENT:
            case MessageCode.EVENT_TYPE_SUBSCRIBE:
                log.info("这是扫码事件！");
                return processEvent(messageDTO);
            case MessageCode.REQ_MESSAGE_TYPE_VOICE:
                log.info("这是语音消息！");
                return "这是语音消息!";
            case MessageCode.REQ_MESSAGE_TYPE_VIDEO:
                log.info("这是视频消息！");
                return "这是视频消息！";
            case MessageCode.REQ_MESSAGE_TYPE_LOCATION:
                log.info("这是位置消息！");
                return "这是位置消息";
            case MessageCode.REQ_MESSAGE_TYPE_LINK:
                log.info("这是链接消息！");
                return "这是链接消息！";
            case MessageCode.REQ_MESSAGE_TYPE_IMAGE:
                log.info("这是图片消息！");
                return "这是图片消息！";
            default:
                return ""; // 或适当进行默认处理
        }
    }

    private MessageDTO mapToDTO(Map<String, String> paramMap) {
        MessageDTO dto = new MessageDTO();
        dto.setFromUserName(paramMap.get("ToUserName"));
        dto.setToUserName(paramMap.get("FromUserName"));
        dto.setMsgType(paramMap.get("MsgType"));
        dto.setCreateTime(Long.parseLong(paramMap.get("CreateTime")));
        if (dto.getMsgType().equals(MessageCode.REQ_MESSAGE_TYPE_TEXT)) {
            dto.setMsgId(Long.parseLong(paramMap.get("MsgId")));
            dto.setContent(paramMap.get("Content"));
        }
        if (dto.getMsgType().equals(MessageCode.REQ_MESSAGE_TYPE_EVENT)) {
            dto.setEventkey(paramMap.get("EventKey"));
            dto.setTicket(paramMap.get("Ticket"));
        }
        return dto;
    }


    // 文本消息处理
    private String processTextMessage(MessageDTO messageDTO) throws IllegalAccessException, InstantiationException {
        BaseMessage baseMessage = null;
        baseMessage = MessageAttributeSetter.setTextAttribute(messageDTO, TextMessage.class);
        //向下转型
        TextMessage textMessage = (TextMessage) baseMessage;
        String content = messageDTO.getContent();
        //向文字消息实体类添加私有的属性数据
        textMessage.setContent("感谢您关注HearTech，很高兴为您服务！\r\n您的信息内容为：" + content);
        //这里为生成xml数据的类，需要提供一个要生成xml数据的实体类，下文放代码
        return messageXmlService.textMessageToXml(textMessage);
    }

    private String processEvent(MessageDTO messageDTO) throws IllegalAccessException, InstantiationException {
        BaseMessage baseMessage = null;
        baseMessage = MessageAttributeSetter.setEventAttribute(messageDTO, TextMessage.class);
        TextMessage textMessage = (TextMessage) baseMessage;
        String eventKeyValue = messageDTO.getEventkey();
        log.info("关注的场景值：" + eventKeyValue);

        /*
        当事件为关注时，场景值会包含前缀"qrscene_"
        检查EventKey是否包含前缀"qrscene_"
        如果包含，则移除该前缀
        */
        if (eventKeyValue.startsWith("qrscene_")) {
            eventKeyValue = eventKeyValue.substring("qrscene_".length());
        }

        // 拆分 UUID——站点id 和 str-二维码
        int lastHyphenIndex = eventKeyValue.lastIndexOf('-');
        String uuidPart = eventKeyValue.substring(0, lastHyphenIndex);
        String strPart = eventKeyValue.substring(lastHyphenIndex + 1);

        // 检查本地二维码状态
        if (!qrCodeStateManager.tryProcessQrCode(strPart)) {
            textMessage.setContent("链接已失效，请重新扫码");
            log.info("该二维码已经被处理过");
            return messageXmlService.eventToXmlText(textMessage);
        }

        try {
            // 获取远程二维码状态
            String strUrl = WxCode.get_str + "?random_str=" + strPart;
            QrStrState response = qrCodeService.sendGetRequest(strUrl);
            int stateValue = response.getState();

            // 根据二维码状态进行处理
            if (stateValue == 1) {
                // 向文字消息实体类添加私有的属性数据
                textMessage.setContent("链接已失效，请重新扫码");
                return messageXmlService.eventToXmlText(textMessage);
            } else {
                String updataStrUrl = WxCode.update_str;
                // 格式化 post 参数
                String postParams = "random_str=" + URLEncoder.encode(strPart, StandardCharsets.UTF_8) +
                        "&state=" + URLEncoder.encode(String.valueOf(1), StandardCharsets.UTF_8);
                qrCodeService.sendPostRequest(updataStrUrl, postParams);

                // 构建URL
                String baseUrl = "https://www.heartech-test.tech/info_collect/";
                String url = baseUrl + "?id=" + uuidPart + "&str=" + strPart;
                textMessage.setContent(url);
                return messageXmlService.eventToXml(textMessage);
            }
        } finally {
            // 释放二维码
            qrCodeStateManager.releaseQrCode(strPart);
        }

    }
}
